package com.zhiwu.uhf.ui.fragment;

import static com.zhiwu.uhf.KeyData.MARK_LOCAL;
import static com.zhiwu.uhf.KeyData.MARK_RECYCLABLE;
import static com.zhiwu.uhf.KeyData.MARK_ROUTES;
import static com.zhiwu.uhf.KeyData.URL_RECYCLABLE;
import static com.zhiwu.uhf.KeyData.URL_ROUTES;
import static com.zhiwu.uhf.util.Base64Util.decodeToString;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.zhiwu.uhf.MainActivity;
import com.zhiwu.uhf.R;
import com.zhiwu.uhf.adapter.RecycleAdapter;
import com.zhiwu.uhf.data.PublicData;
import com.zhiwu.uhf.entity.BeanInfo;
import com.zhiwu.uhf.ui.base.BaseFragment;
import com.zhiwu.uhf.util.DataInterface;
import com.zhiwu.uhf.util.GsonTypeAdapterFactory;
import com.zhiwu.uhf.util.LogUtil;
import com.zhiwu.uhf.util.UtilSound;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class InventoryFragment extends BaseFragment {

    @BindView(R.id.button_inventory)
    Button btnInventory ;
    @BindView(R.id.button_clean)
    Button btnClean ;
    @BindView(R.id.recycle)
    RecyclerView recycle;
    @BindView(R.id.etSearch)
    EditText etSearch;
    @BindView(R.id.btnSearch)
    Button btnSearch;

    private String searchContent;
    private MainActivity mainActivity ;
    private KeyReceiver keyReceiver;

    private Gson gson = new GsonBuilder().registerTypeAdapterFactory(new GsonTypeAdapterFactory()).create();
    private RecycleAdapter recycleApter;
    private List<BeanInfo.Data> beanList = new ArrayList<>();
    private List<BeanInfo.Data> origBeanList = new ArrayList<>();
    private final int MSG_INVENTORY = 1 ;
    private final int MSG_SCAN_ENABLED = 1002;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private final static int MIN_CLICK_DELAY_TIME = 1500;
    private static long lastClickTime;

    //1=南京片区 2=中转片区
    private Integer selectedArea = 1;

    private Handler handler = new Handler(){
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case MSG_INVENTORY:
                    break ;
                case MSG_SCAN_ENABLED:
                    List<BeanInfo.Data> checkedList = getCheckedList();
                    if(!checkedList.isEmpty()) {
                        btnInventory.setEnabled(true);
                    } else {
                        btnInventory.setEnabled(true);
                    }
                    break ;
            }
        }
    };

    private List<BeanInfo.Data> getCheckedList() {
        List<BeanInfo.Data> checkedList = new ArrayList<>();
        PublicData.checkedMap.clear();
//        for(BeanInfo.Data data : beanList) {
//            if(Boolean.TRUE.equals(data.isChecked())) {
//                checkedList.add(data);
//                PublicData.checkedMap.put(data.getRoute_code(), data.getRoute_name());
//            }
//        }
        //这里改成 选择南京片区 自动选中带南京的线路 中转片区不带南京的线路
        for(BeanInfo.Data data : beanList) {
            String routeName = data.getRoute_name();
            boolean isNanjingArea = routeName.contains("南京") || routeName.contains("句容");
            if(selectedArea == 1) {
                if(isNanjingArea) {
                    checkedList.add(data);
                    PublicData.checkedMap.put(data.getRoute_code(), routeName);
                }
            } else if(selectedArea == 2) {
                if(!isNanjingArea) {
                    checkedList.add(data);
                    PublicData.checkedMap.put(data.getRoute_code(), routeName);
                }
            }
        }
        return checkedList;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainActivity = (MainActivity) getActivity();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_inventory, container, false) ;
        ButterKnife.bind(this, view);
        init();
        UtilSound.initSoundPool(mainActivity);
        return view;
    }

    void init(){
//        mainActivity.loadingView.start();
        btnInventory.setEnabled(true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recycle.setLayoutManager(layoutManager);
        recycle.setHasFixedSize(true);
        recycle.setItemAnimator(null);
        recycleApter = new RecycleAdapter(getActivity(), beanList);
        recycle.setAdapter(recycleApter);
        initAllDriverRoute();
        itemclick();
    }
    @Override
    public void onResume() {
        super.onResume();
        if (mainActivity.mUhfrManager != null) {
            mainActivity.mUhfrManager.setCancleInventoryFilter();
        }
        //
        registerKeyCodeReceiver();
    }

    @Override
    public void onPause() {
        super.onPause();
        mainActivity.unregisterReceiver(keyReceiver);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @OnClick(R.id.button_clean)
    public void clear() {
        if (isFastClick()){
            PublicData.recyclableMap.clear();
            PublicData.routeMap.clear();
            PublicData.epcMap.clear();
            PublicData.comparedMap.clear();
            PublicData.routeCodeNameMap.clear();
            PublicData.comparedList.clear();
            PublicData.comparedGreenList.clear();
            initAllDriverRoute();
        }
    }

    @OnClick(R.id.button_inventory)
    public void inventory() {
        selectedArea = 1;
        List<BeanInfo.Data> checkedList = getCheckedList();
        if(checkedList.isEmpty()) {
            getActivity().runOnUiThread(() -> showToast("请选择线路"));
            return;
        }
        PublicData.checkedList.clear();
        PublicData.checkedList.addAll(checkedList);
        mainActivity.navController.navigate(R.id.nav_epc_list);

    }
    @OnClick(R.id.button_inventory_transit)
    public void inventoryTransit() {
        selectedArea = 2;
        List<BeanInfo.Data> checkedList = getCheckedList();
        if(checkedList.isEmpty()) {
            getActivity().runOnUiThread(() -> showToast("请选择线路"));
            return;
        }
        PublicData.checkedList.clear();
        PublicData.checkedList.addAll(checkedList);
        mainActivity.navController.navigate(R.id.nav_epc_list);

    }
    @OnClick(R.id.btnSearch)
    public void search() {
        if(StringUtils.isBlank(searchContent)) {
            return;
        }
        beanList.clear();
        for(BeanInfo.Data data : origBeanList) {
            if(data.getRoute_name().toLowerCase().contains(searchContent)) {
                beanList.add(data);
            }
        }
        recycleApter.notifyDataSetChanged();
    }

    private void initAllDriverRoute() {
        Log.i("com.zhiwu.data", "----开始初始化线路数据----");
        Date curDate =  new Date(System.currentTimeMillis());
        String time  = dateFormat.format(curDate);
        Call call = new DataInterface().getData(MARK_ROUTES, MARK_LOCAL,time,URL_ROUTES);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("tag", "----getAllDriverRoute----"+e);
                getActivity().runOnUiThread(() -> showToast("获取线路数据失败: " + e));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String Str = response.body().string();
                    parsedAllDriverRoute(Str);
                }else {
                    getActivity().runOnUiThread(() -> showToast("getAllDriverRoute_failed"));
                }
            }
        });
    }

    private void parsedAllDriverRoute(String str) {
        BeanInfo beanInfo = gson.fromJson(str,BeanInfo.class);
        if ("1".equals(beanInfo.getStatus())){
            String data = decodeToString(beanInfo.getData());
            List<BeanInfo.Data> jsonListObject = gson.fromJson(data, new TypeToken<List<BeanInfo.Data>>(){}.getType());

            //todo --start-- 测试数据 记得删除
//            for(int i = 0; i< 15; i++) {
//                List<BeanInfo.Data> testData = gson.fromJson(data, new TypeToken<List<BeanInfo.Data>>(){}.getType());
//                for(int j =0; j<testData.size();j++) {
//                    BeanInfo.Data test = testData.get(j);
//                    test.setRoute_code(test.getRoute_code() + i + j);
//                    test.setRoute_name(test.getRoute_name() + i + j);
//                    test.setDriver_code(test.getDriver_code() + i + j);
//                    test.setDriver_name(test.getDriver_name() + i + j);
//                }
//                jsonListObject.addAll(testData);
//
//            }
            //todo --end-- 测试数据 记得删除
            origBeanList.clear();
            origBeanList.addAll(jsonListObject);
            beanList.clear();
            beanList.addAll(jsonListObject);
            initRecyclableContainers();
            getActivity().runOnUiThread(() -> recycleApter.notifyDataSetChanged());
        }else {
            getActivity().runOnUiThread(() -> showToast(decodeToString(beanInfo.getMsg())));
        }
    }

    private void initRecyclableContainers() {
        Date curDate =  new Date(System.currentTimeMillis());
        String time  = dateFormat.format(curDate);
        Call call = new DataInterface().getData(MARK_RECYCLABLE, MARK_LOCAL,time, URL_RECYCLABLE);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("tag", "------getRecyclableContainers-----"+e);
                getActivity().runOnUiThread(() -> showToast("获取所有可回收箱号失败：" + e));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String Str = response.body().string();
                    parseRecyclableContainers(Str);
                }else {
                    getActivity().runOnUiThread(() -> showToast("getRecyclableContainers_failed"));
                }
            }
        });
    }
    private void parseRecyclableContainers(String str) {
        BeanInfo beanInfo = gson.fromJson(str,BeanInfo.class);

        //todo --start-- 测试数据 记得删除
//        beanInfo.setTotal(2);
//        beanInfo.setData("W3sicm91dGVfY29kZSI6IkxETTAwMDAxMzY1Iiwicm91dGVfbmFtZSI6IuS4gOWPt+i9pjXnur8iLCJjb250YWluZXJzIjoiMTAwMDAxLDEwMDAwMiwxMDAwMDMsMTAwMDA0LDEwMDAwNSJ9LHsicm91dGVfY29kZSI6IkxETTAwMDAxNTgxIiwicm91dGVfbmFtZSI6IuWugemYs+S6jOWNgeS6jOWPt+i9pjHnur8iLCJjb250YWluZXJzIjoiMDAwMDAxLDAwMDAwMiwwMDAwMDMsMDAwMDA0LDAwMDAwNSwwMDAwMDYsMDAwMDA3In1d");
        //todo --end-- 测试数据 记得删除

        if ("1".equals(beanInfo.getStatus())){
            if (beanInfo.getTotal() > 0){
                PublicData.recyclableMap.clear();
                String data = decodeToString(beanInfo.getData());
                List<BeanInfo.Data> jsonListObject = gson.fromJson(data, new TypeToken<List<BeanInfo.Data>>(){}.getType());
                for(BeanInfo.Data routeData : jsonListObject) {
                    Map<String, Integer> containersMap = new HashMap<>();
                    String[] containers = routeData.getContainers().split(",");
                    for(String container : containers) {
                        PublicData.epcMap.put(container, routeData.getRoute_code());
                        containersMap.put(container, 0);
                    }
                    PublicData.recyclableMap.put(routeData.getRoute_code(), containersMap);
                }
                //把线路转成map 方便匹配
                for(int i = 0; i < beanList.size(); i++) {
                    BeanInfo.Data routeData = beanList.get(i);
                    Map<String, Integer> containersMap = PublicData.recyclableMap.get(routeData.getRoute_code());
                    if(containersMap == null) {
                        containersMap = new HashMap<>();
                    }
                    routeData.setTotal(containersMap.size());
                    //保存路线和箱号的关系
                    PublicData.routeMap.put(routeData.getRoute_code(), containersMap);
                    PublicData.routeCodeNameMap.put(routeData.getRoute_code(), routeData.getRoute_name());
                }

                Log.i("com.zhiwu.data", "----结束初始化线路数据----");
                getActivity().runOnUiThread(() -> {
                    recycleApter.notifyDataSetChanged();
                });
            }
        }else {
            getActivity().runOnUiThread(() -> showToast(decodeToString(beanInfo.getMsg())));
        }
    }

    private void registerKeyCodeReceiver() {
        keyReceiver = new KeyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.rfid.FUN_KEY");
        filter.addAction("android.intent.action.FUN_KEY");
        mainActivity.registerReceiver(keyReceiver, filter);
    }


    //
    private class KeyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int keyCode = intent.getIntExtra("keyCode", 0);
            LogUtil.e("keyCode = " + keyCode);
            if (keyCode == 0) {
                keyCode = intent.getIntExtra("keycode", 0);
            }
            boolean keyDown = intent.getBooleanExtra("keydown", false);
            if (keyDown) {
//                ToastUtils.showText("KeyReceiver:keyCode = down" + keyCode);
            } else {
//                ToastUtils.showText("KeyReceiver:keyCode = up" + keyCode);
                switch (keyCode) {
                    case KeyEvent.KEYCODE_F1:
                        break;
                    case KeyEvent.KEYCODE_F2:
                        break;
                    case KeyEvent.KEYCODE_F5:
                        break;
                    case KeyEvent.KEYCODE_F3://C510x
                    case KeyEvent.KEYCODE_F4://6100
                    case KeyEvent.KEYCODE_F7://H3100
                        inventory();
                        break;
                }
            }
        }

    }

    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    private void itemclick() {
        recycleApter.setOnItemClickListener((view, data, position) -> {
        });
        recycleApter.setOnItemmultiple((view, data, position) -> {
            handler.sendEmptyMessage(MSG_SCAN_ENABLED);
            recycleApter.notifyDataSetChanged();
        });

        recycleApter.setOnItemshowDialog((view, data, position) -> {
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 文本改变之前的处理
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 文本正在改变的处理
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 文本改变之后的处理
                searchContent = s.toString().toLowerCase();
                if(StringUtils.isBlank(searchContent)) {
                    btnSearch.setEnabled(false);
                    beanList.clear();
                    beanList.addAll(origBeanList);
                    recycleApter.notifyDataSetChanged();
                } else {
                    btnSearch.setEnabled(true);
                }
                // 这里可以根据text的内容进行相应的操作
            }
        });

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    // The user pressed the Enter key.
                    // Perform your desired action here, such as submitting the text.
                    search();
                    return true; // Consume the event
                }
                return false; // Don't consume the event
            }
        });

    }

}